package com.ruoyi.service.impl;

import com.ruoyi.service.FileUploadService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Value("${file.upload.path:./uploads}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/uploads}")
    private String urlPrefix;

    // 文件大小限制（10MB）
    private static final long MAX_FILE_SIZE = 10 * 1024 * 1024;

    // 图片大小限制（5MB）
    private static final long MAX_IMAGE_SIZE = 5 * 1024 * 1024;

    // 允许的文件类型
    private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList(
            "application/pdf",
            "application/msword",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "application/vnd.ms-excel",
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "text/plain"
    );

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !ALLOWED_FILE_TYPES.contains(contentType)) {
            throw new IllegalArgumentException("不支持的文件类型");
        }

        // 验证文件大小
        if (file.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小不能超过 10MB");
        }

        return upload(file, "files");
    }

    @Override
    public String uploadImage(MultipartFile file) throws Exception {
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("文件类型必须是图片");
        }

        // 验证文件大小
        if (file.getSize() > MAX_IMAGE_SIZE) {
            throw new IllegalArgumentException("图片大小不能超过 5MB");
        }

        return upload(file, "images");
    }

    private String upload(MultipartFile file, String subDir) throws IOException {
        // 获取绝对路径
        String absolutePath = new File(uploadPath).getAbsolutePath();
        String dirPath = absolutePath + File.separator + subDir;

        // 确保上传目录存在
        Path dir = Paths.get(dirPath);
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + extension;

        // 保存文件
        Path filePath = dir.resolve(newFilename);
        try (InputStream inputStream = file.getInputStream()) {
            Files.copy(inputStream, filePath);
        } catch (IOException e) {
            throw new IOException("文件保存失败", e);
        }

        // 返回访问URL
        return urlPrefix + "/" + subDir + "/" + newFilename;
    }
}
